<template>
  <div>
    <van-cell v-for="item in suggestion" :key="item" @click="onSearch(item)">
      <template>
        <van-icon name="close" />
      </template>
      <template #title>
        <div v-html="highText(item)" />
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getsuggestion } from '@/api/search.js'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestion: []
    }
  },
  watch: {
    searchText: {
      immediate: true,
      handler(newval) {
        if (this.times) {
          clearTimeout(this.times)
        }
        // console.log(newval)
        this.times = setTimeout(async() => {
          const res = await getsuggestion(newval)
          console.log(res)
          this.suggestion = res.options
        }, 500)
      }
    }
  },
  beforeDestroy() {
    clearTimeout(this.times)
  },

  created() {

  },

  methods: {
    highText(item) {
      const str = '<span style="color:red">' + this.searchText + '</span>'
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, str)
    },
    onSearch(item) {
      console.log(item)
      this.$emit('onSearch', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
